"""
    a login window
    connect to mysql
    key features:
    1.check if account is used
    2.check if passwords inconsistent
    3.insert a new account to mysql
"""

import sys

from PyQt5.QtCore import Qt, QPoint, pyqtSignal
from PyQt5.QtGui import QMouseEvent, QCursor
from PyQt5.QtWidgets import QMainWindow, QApplication

from loginpage.enroll import Ui_enrollwin
from loginpage.login import Ui_loginwin
from main import MainWindow
import pymysql

from utils.CustomMessageBox import MessageBox


class enroll_window(QMainWindow, Ui_enrollwin):
    # connect to mysql
    mysql = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123456',
        port=3306,
        db='imagerecognition',
        autocommit=True,  # auto commit
    )
    cursor = mysql.cursor()
    # search username statement
    sql = "SELECT * FROM users WHERE username=%s"
    # insert new account statement
    insql = "INSERT INTO users(username,password) values(%s,%s)"
    send = pyqtSignal()

    def __init__(self, parent=None):
        super(enroll_window, self).__init__(parent)
        self.setupUi(self)
        self.m_flag = False
        # no border and transparent
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(Qt.FramelessWindowHint)
        # closeButton signal connect to slot
        self.closeButton.clicked.connect(self.close)
        # minButton signal connect to slot
        # this window can not be zoom
        self.minButton.clicked.connect(self.showMinimized)
        # pushButton signal connect to slot
        self.pushButton.clicked.connect(self.check)
        # backButton signal connect to slot
        self.backbutton.clicked.connect(self.back)

    def back(self):
        # use signal to prompt login window to show
        self.send.emit()
        self.hide()

    def check(self):
        # user name
        name = self.name.text()
        # input password first time
        p1 = self.password.text()
        # input password second time
        p2 = self.password2.text()
        # search in mysql for the user name
        self.cursor.execute(self.sql, name)
        a = self.cursor.fetchone()
        # the account is existed
        if a is not None:
            MessageBox(
                self.closeButton, title='Tips', text='Account Existed!', time=1500, auto=True).exec_()
            self.name.clear()
        # Passwords Inconsistent
        elif p1 != p2:
            MessageBox(
                self.closeButton, title='Tips', text='Passwords Inconsistent!', time=1500, auto=True).exec_()
            self.password.clear()
            self.password2.cursor()
        # no problem, insert the new account to mysql
        else:
            self.cursor.execute(self.insql, (name, p1))
            MessageBox(
                self.closeButton, title='Tips', text='Enroll Successfully!', time=1500, auto=True).exec_()
            # use signal to prompt login window to show
            self.send.emit()
            self.hide()

    # rewrite events about mouse to realize window moving
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()
            event.accept()

    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(Qt.ArrowCursor))


class login_window(QMainWindow, Ui_loginwin):
    # conncet to localhost mysql
    mysql = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123456',
        port=3306,
        db='imagerecognition',
        autocommit=True,
    )
    # just like above
    cursor = mysql.cursor()
    sql = "SELECT * FROM users WHERE username=%s"
    insql = "INSERT INTO users(username,password) values(%s,%s)"
    send_id = pyqtSignal(int)

    def __init__(self, parent=None):
        super(login_window, self).__init__(parent)
        self.setupUi(self)
        self.m_flag = False
        # no border and transparent
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(Qt.FramelessWindowHint)
        # closeButton signal connect to slot
        self.closeButton.clicked.connect(self.close)
        # minButton signal connect to slot
        # this window can not be zoom
        self.minButton.clicked.connect(self.showMinimized)
        # if login successfully show the main window,otherwise pop up a prompt window
        self.pushButton.clicked.connect(self.openMainWin)
        # open enroll window
        self.Enroll.clicked.connect(self.enroll)
        # include a enroll window
        self.enroll_win = enroll_window()
        # enroll window closed , login window show
        self.enroll_win.send.connect(self.show)
        # include a main window
        self.mainwindow = MainWindow()
        # main window send a login signal
        self.mainwindow.send_login.connect(self.show)

    # open enroll window and hide self
    def enroll(self):
        self.enroll_win.show()
        self.hide()

    def openMainWin(self):
        # user name
        name = self.name.text()
        # input password
        password = self.password.text()
        # search for the account in mysql
        self.cursor.execute(self.sql, name)
        a = self.cursor.fetchone()
        # no account named name
        if a is None:
            MessageBox(
                self.closeButton, title='Tips', text='No account!', time=1500, auto=True).exec_()
            # clear input or the user to input again
            self.name.clear()
            self.password.clear()
        # wrong password
        elif a[2] != password:
            MessageBox(
                self.closeButton, title='Tips', text='Wrong Password!', time=1500, auto=True).exec_()
            # clear input or the user to input again
            self.password.clear()
        # login successfully
        else:
            MessageBox(
                self.closeButton, title='Tips', text='Login Successfully!', time=1500, auto=True).exec_()
            # clear input or the user to input again
            self.name.clear()
            self.password.clear()
            # deliver user id
            self.mainwindow.userid = a[0];
            # load user information
            self.mainwindow.loaduserdata()
            self.mainwindow.show()
            self.close()

    # rewrite events about mouse to realize window moving
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()
            event.accept()

    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(Qt.ArrowCursor))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    a = login_window()
    a.show()
    sys.exit(app.exec_())
